package com.android.clinic.app.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseFragment;
import com.android.clinic.app.entity.NoticeInfo;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.doctor.AskQuestionWithDoctorActivity;
import com.android.clinic.app.ui.doctor.DoctorAdvisoryActivity;
import com.android.clinic.app.ui.doctor.DoctorMessageActivity;
import com.android.clinic.app.ui.doctor.SystemMessageActivity;
import com.android.clinic.app.ui.doctor.MyReportListActivity;
import com.android.clinic.app.ui.widget.UIAlertView;
import com.android.clinic.app.utils.Constants;
import com.android.clinic.app.utils.PermissionUtils;
import com.android.clinic.app.utils.Toasty;
import com.android.clinic.app.utils.Utils;
import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.kennyc.view.MultiStateView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by cheng on 2018/1/26.
 */
public class MessageFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {

    private Toolbar toolbar;
    private Intent intent;

    private SwipeToLoadLayout swipeToLoadLayout;
    private ListView listView;
    private NoticeAdapter mAdapter;
    private int pageSize = 10;  // 每页请求数量
    private int pageNum = 1; // 当前页数

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_message;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ((MainActivity)getActivity()).mImmersionBar.setTitleBar(getActivity(), toolbar);
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        swipeToLoadLayout = (SwipeToLoadLayout) findViewById(R.id.swipeToLoadLayout);
        listView = (ListView) findViewById(R.id.swipe_target);
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);

        View headerView = getActivity().getLayoutInflater().inflate(R.layout.view_message_header_view, null);
        mAdapter = new NoticeAdapter();
        listView.setAdapter(mAdapter);

        RelativeLayout layHousekeeperPhone = (RelativeLayout) headerView.findViewById(R.id.layout_housekeeper_phone);
        RelativeLayout layDoctorRecommend = (RelativeLayout) headerView.findViewById(R.id.layout_doctor_recommend);
        RelativeLayout layReport = (RelativeLayout) headerView.findViewById(R.id.layout_report);
        layHousekeeperPhone.setOnClickListener(v -> PermissionUtils.applyCallPhone(getActivity(), new PermissionUtils.CallBack() {
            @Override
            public void onGuarantee() {
                UIAlertView.callPhoneDialog(getActivity(), "管家电话", "4001883525");
            }

            @Override
            public void onDeny() {

            }
        }));
        layDoctorRecommend.setOnClickListener(v -> {
            Intent intent1 = new Intent(getActivity(), AskQuestionWithDoctorActivity.class);
            intent1.putExtra("doctorId", "");
            startActivity(intent1);
        });
        layReport.setOnClickListener(v -> startActivity(new Intent(getActivity(), MyReportListActivity.class)));

        listView.addHeaderView(headerView);
    }

    @Override
    protected void loadData() {
       getNoticeList();
    }

    /**
     * 获取消息列表
     */
    private void getNoticeList() {
        HttpClient.getHttpService().getNoticeList(ClinicApplication.getUserInfo().getId(), pageSize, pageNum)
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        refreshComplete();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            List<NoticeInfo> noticeInfoList = JSON.parseArray(jsonObject.optJSONArray("result").toString(),
                                    NoticeInfo.class);
                            if (noticeInfoList.size() > 0) {
                                setMultiStateView(MultiStateView.VIEW_STATE_CONTENT);
                                mAdapter.setNoticeList(noticeInfoList);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        refreshComplete();
                        Toasty.showShort(getActivity(), message);
                    }
                });
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        new Handler().postDelayed(this::getNoticeList, 500);
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        new Handler().postDelayed(this::getNoticeList, 500);
    }

    private void refreshComplete() {
        if (null != swipeToLoadLayout) {
            if (swipeToLoadLayout.isRefreshing()) {
                swipeToLoadLayout.setRefreshing(false);
            }
            if (swipeToLoadLayout.isLoadingMore()) {
                swipeToLoadLayout.setLoadingMore(false);
            }
        }
    }

    private class NoticeAdapter extends BaseAdapter {

        private List<NoticeInfo> noticeList = new ArrayList<>();

        public void setNoticeList(List<NoticeInfo> noticeList) {
            this.noticeList = noticeList;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return noticeList.size();
        }

        @Override
        public NoticeInfo getItem(int position) {
            return noticeList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LinearLayout.inflate(getActivity(), R.layout.item_list_message, null);
                holder = new ViewHolder();
                holder.ivPic = (ImageView) convertView.findViewById(R.id.iv_pic);
                holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
                holder.tvContent = (TextView) convertView.findViewById(R.id.tv_content);
                holder.tvTime = (TextView) convertView.findViewById(R.id.tv_time);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (getItem(position).getType().equals(Constants.SYSTEM)) {
                holder.ivPic.setImageResource(R.drawable.icon_msg_system);
            } else if (getItem(position).getType().equals(Constants.ORDER)) {
                holder.ivPic.setImageResource(R.drawable.icon_msg_consume);
            } else if (getItem(position).getType().equals(Constants.MESSAGE)) {
                holder.ivPic.setImageResource(R.drawable.icon_msg_doctor_info);
            } else {
                holder.ivPic.setImageResource(R.drawable.icon_msg_doctor_reply);
            }
            holder.tvTitle.setText(getItem(position).getTitle());
            holder.tvContent.setText(getItem(position).getContent());
            holder.tvTime.setText(Utils.getFormatTime(getItem(position).getCreateTime()));

            convertView.setOnClickListener(v -> {
                // 系统消息
                if (getItem(position).getType().equals(Constants.SYSTEM)) {
                    intent = new Intent(getActivity(), SystemMessageActivity.class);
                    intent.putExtra("message", mAdapter.getItem(position));
                    startActivity(intent);
                }
                // 医生回复
                else if (getItem(position).getType().equals(Constants.ANSWER)) {
                    if ("2".equals(getItem(position).getStatus())) {
                        showToast("图文问诊已结束, 请重新购买!");
                        return;
                    }
                    intent = new Intent(getActivity(), DoctorAdvisoryActivity.class);
                    intent.putExtra("inquireId", mAdapter.getItem(position).getInquireId());
                    startActivity(intent);
                }
                // 医生消息
                else if (getItem(position).getType().equals(Constants.MESSAGE)) {
                    intent = new Intent(getActivity(), DoctorMessageActivity.class);
                    intent.putExtra("message", mAdapter.getItem(position));
                    startActivity(intent);
                }
            });

            return convertView;
        }

        class ViewHolder {
            ImageView ivPic;
            TextView tvTitle, tvContent, tvTime;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getNoticeList();
        }
    }
}
